package com.hyphenate.easeui.ui;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.TextView;

import com.hyphenate.EMConnectionListener;
import com.hyphenate.EMConversationListener;
import com.hyphenate.EMError;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.easeui.ModelBean;
import com.hyphenate.easeui.R;
import com.hyphenate.easeui.UserInfoDto;
import com.hyphenate.easeui.utils.EaseUserUtils;
import com.hyphenate.easeui.widget.EaseConversationList;
import com.orhanobut.hawk.Hawk;
import com.simga.library.http.APIException;
import com.simga.library.http.Event;
import com.simga.library.http.HttpHelper;
import com.simga.library.http.Request;
import com.simga.library.utils.HawkKey;
import com.simga.library.utils.LogUtil;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;

import io.reactivex.Observable;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.POST;

/**
 * conversation list fragment
 */
public class EaseConversationListFragment extends EaseBaseFragment {
    private final static int MSG_REFRESH = 2;
    protected EditText query;
    protected ImageButton clearSearch;
    protected boolean hidden;
    protected List<ModelBean> conversationList = new ArrayList<>();
    protected EaseConversationList conversationListView;
    protected TextView tvNoData;
    protected FrameLayout errorItemContainer;

    protected boolean isConflict;

    protected EMConversationListener convListener = new EMConversationListener() {

        @Override
        public void onCoversationUpdate() {
            refresh();
        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.ease_fragment_conversation_list, container, false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        if (savedInstanceState != null && savedInstanceState.getBoolean("isConflict", false))
            return;
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    protected void initView() {
        hideTitleBar();
        inputMethodManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        conversationListView = (EaseConversationList) getView().findViewById(R.id.list);
        tvNoData = (TextView) getView().findViewById(R.id.tv_noData);
        query = (EditText) getView().findViewById(R.id.query);
        clearSearch = (ImageButton) getView().findViewById(R.id.search_clear);
        errorItemContainer = (FrameLayout) getView().findViewById(R.id.fl_error_item);
    }

    @Override
    protected void setUpView() {
//        loadConversationList();
        conversationListView.init(conversationList);
        if (listItemClickListener != null) {
            conversationListView.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    EMConversation conversation = conversationListView.getItem(position).getConversation();
                    listItemClickListener.onListItemClicked(conversation);
                }
            });
        }
        EMClient.getInstance().addConnectionListener(connectionListener);
        query.addTextChangedListener(new TextWatcher() {
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                conversationListView.filter(s);
                if (s.length() > 0) {
                    clearSearch.setVisibility(View.VISIBLE);
                } else {
                    clearSearch.setVisibility(View.INVISIBLE);
                }
            }

            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            public void afterTextChanged(Editable s) {
            }
        });
        clearSearch.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                query.getText().clear();
                hideSoftKeyboard();
            }
        });

        conversationListView.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                hideSoftKeyboard();
                return false;
            }
        });
    }


    protected EMConnectionListener connectionListener = new EMConnectionListener() {

        @Override
        public void onDisconnected(int error) {
            if (error == EMError.USER_REMOVED || error == EMError.USER_LOGIN_ANOTHER_DEVICE || error == EMError.SERVER_SERVICE_RESTRICTED
                    || error == EMError.USER_KICKED_BY_CHANGE_PASSWORD || error == EMError.USER_KICKED_BY_OTHER_DEVICE) {
                isConflict = true;
            } else {
                handler.sendEmptyMessage(0);
            }
        }

        @Override
        public void onConnected() {
            handler.sendEmptyMessage(1);
        }
    };
    private EaseConversationListItemClickListener listItemClickListener;

    protected Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case 0:
                    onConnectionDisconnected();
                    break;
                case 1:
                    onConnectionConnected();
                    break;

                case MSG_REFRESH: {
                    conversationList.clear();
                    loadConversationList();
                    break;
                }
                default:
                    break;
            }
        }
    };

    /**
     * connected to server
     */
    protected void onConnectionConnected() {
        errorItemContainer.setVisibility(View.GONE);
    }

    /**
     * disconnected with server
     */
    protected void onConnectionDisconnected() {
        errorItemContainer.setVisibility(View.VISIBLE);
    }


    /**
     * refresh ui
     */
    public void refresh() {
        if (!handler.hasMessages(MSG_REFRESH)) {
            handler.sendEmptyMessage(MSG_REFRESH);
        }
    }

    /**
     * load conversation list
     *
     * @return +
     */

    Handler myHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 9595) {
                conversationList.clear();
                ListSort(modellist);
                conversationList.addAll(modellist);
                conversationListView.refresh();

            }
        }
    };

    private static void ListSort(List<ModelBean> list) {
        Collections.sort(list, new Comparator<ModelBean>() {
            @Override
            public int compare(ModelBean o1, ModelBean o2) {
                try {
                    Date dt1 = new Date(o1.getConversation().getLastMessage().getMsgTime());
                    Date dt2 = new Date(o2.getConversation().getLastMessage().getMsgTime());
                    if (dt1.before(dt2)) {
                        return 1;
                    } else {
                        return -1;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return 0;
            }
        });
    }


    List<ModelBean> modellist;
    int num = 0;

    protected void loadConversationList() {
        modellist = new ArrayList<>();
        num = 0;
        Map<String, EMConversation> conversations = EMClient.getInstance().chatManager().getAllConversations();
        final List<Pair<Long, EMConversation>> sortList = new ArrayList<>();
        synchronized (conversations) {
            for (EMConversation conversation : conversations.values()) {
                if (conversation.getAllMessages().size() != 0) {
                    sortList.add(new Pair<>(conversation.getLastMessage().getMsgTime(), conversation));
                }
            }
        }
        try {
            sortConversationByLastChatTime(sortList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (sortList.size() == 0) {
            tvNoData.setVisibility(View.VISIBLE);
            conversationListView.setVisibility(View.GONE);
        } else {
            tvNoData.setVisibility(View.GONE);
            conversationListView.setVisibility(View.VISIBLE);
        }
        conversationList.clear();
        ListSort(modellist);
        conversationList.addAll(modellist);
        conversationListView.refresh();

        for (int i = 0; i < sortList.size(); i++) {
            num++;
            final Pair<Long, EMConversation> sortItem = sortList.get(i);
            getHxRequest(new onCallBackHxUser() {
                @Override
                public void complete(UserInfoDto dto) {
                    ModelBean bean = new ModelBean();
                    bean.setConversation(sortItem.second);
                    UserInfoDto userInfo = dto;
                    bean.setNickName(userInfo.getNickname());
                    bean.setAvatar(userInfo.getAvatar());
                    modellist.add(bean);
                    if (num == sortList.size()) {
                        Message msg = new Message();
                        msg.what = 9595;
                        myHandler.sendMessage(msg);
                    }
                }

                @Override
                public void fail(String message) {
                    ModelBean bean = new ModelBean();
                    bean.setConversation(sortItem.second);
                    bean.setNickName("在线客服");
                    bean.setAvatar("https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=301008915,791729930&fm=26&gp=0.jpg");
                    modellist.add(bean);
                    if (num == sortList.size()) {
                        Message msg = new Message();
                        msg.what = 9595;
                        myHandler.sendMessage(msg);
                    }
                }
            }).request(1, HttpHelper.apiHttp.getService(AuthApi.class).
                    getHxInfor(sortItem.second.conversationId()), null, Event.DESTROY);
        }
    }

    /**
     * sort conversations according time stamp of last message
     *
     * @param conversationList
     */
    private void sortConversationByLastChatTime(List<Pair<Long, EMConversation>> conversationList) {
        Collections.sort(conversationList, new Comparator<Pair<Long, EMConversation>>() {
            @Override
            public int compare(final Pair<Long, EMConversation> con1, final Pair<Long, EMConversation> con2) {
                if (con1.first.equals(con2.first)) {
                    return 0;
                } else if (con2.first.longValue() > con1.first.longValue()) {
                    return 1;
                } else {
                    return -1;
                }
            }

        });
    }

    protected void hideSoftKeyboard() {
        if (getActivity().getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
            if (getActivity().getCurrentFocus() != null)
                inputMethodManager.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        this.hidden = hidden;
        if (!hidden && !isConflict) {
            refresh();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (!hidden) {
            refresh();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EMClient.getInstance().removeConnectionListener(connectionListener);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if (isConflict) {
            outState.putBoolean("isConflict", true);
        }
    }

    public interface EaseConversationListItemClickListener {
        /**
         * click event for conversation list
         *
         * @param conversation -- clicked item
         */
        void onListItemClicked(EMConversation conversation);
    }

    /**
     * set conversation list item click listener
     *
     * @param listItemClickListener
     */
    public void setConversationListItemClickListener(EaseConversationListItemClickListener listItemClickListener) {
        this.listItemClickListener = listItemClickListener;
    }


    public static Request getHxRequest(final onCallBackHxUser callBack) {
        Request request = new Request() {
            @Override
            public <T> void onNext(int postCode, T result, Object data) {
                super.onNext(postCode, result, data);
                if (postCode == 1) {
                    callBack.complete((UserInfoDto) result);
                }
            }

            @Override
            public void onError(int postCode, Object data, Throwable e) {
                super.onError(postCode, data, e);
                if(((APIException)e).getDisplayMessage().equals("用户不存在")){
                    callBack.fail(((APIException)e).getDisplayMessage());
                }
            }
        };
        return request;
    }

    public interface onCallBackHxUser {
        void complete(UserInfoDto dto);
        void fail(String message);
    }

    interface AuthApi {

        /**
         * 环信用户信息
         *
         * @param hx_id
         * @return
         */
        @FormUrlEncoded
        @POST("user/userInfo_hx_id.json")
        Observable<UserInfoDto> getHxInfor(@Field("phone") String hx_id);
    }
}
